package cn.qiao.web.aop;

import cn.qiao.web.util.RequestUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class NetworkAspect {

    private static final Logger log = LoggerFactory.getLogger(NetworkAspect.class);

    @Around("bean(*Controller)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();
            return pjp.proceed();
        } finally {
            stopWatch.stop();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (servletRequestAttributes != null) {
                HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
                String remoteAddr = RequestUtil.getRemoteAddr(httpServletRequest);
                String method = httpServletRequest.getMethod();
                String uri = httpServletRequest.getRequestURI();
                log.info("{} {} {} {}ms", remoteAddr, method, uri, stopWatch.getTotalTimeMillis());
            }
        }
    }
}
